<!DOCTYPE html>
<!-- <base href="http://localhost:1024/src"> -->
<style>
  input[type='number']::-webkit-inner-spin-button,
  input[type='number']::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  .options {
    margin-bottom: 2em;
    user-select: none;
  }

  .options input[type='number'] {
    width: 3em;
    text-align: center;
  }

  .operate {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 30px;
  }

  .axios {
    display: block;
  }

  .axios code {
    font-family: Arial, Helvetica, sans-serif;
    display: inline-block;
    padding: 2px 4px;
    background-color: #eeeee8;
    border-radius: 2px;
    font-size: 0.8em;
    margin: 0 4px;
  }
</style>

<div>
  <div class="options">
    <label>
      <input type="checkbox" onchange="toggle(event)" />
      <input type="number" min="16" value="50" onchange="changeDelay(event)" />
      <span>ms 后中断请求</span>
    </label>
  </div>
  <div>
    <label class="axios">
      <input type="radio" name="axios" value="1" checked onchange="selectAxios(event)" />
      <span>采用axios1：原生包装，header追加<code>XHead1: 'first created'</code></span>
    </label>
    <label class="axios">
      <input type="radio" name="axios" value="2" onchange="selectAxios(event)" />
      <span>采用axios2：基于axios1包装，header追加<code>XHead2: 'second created'</code></span>
    </label>
    <label class="axios">
      <input type="radio" name="axios" value="3" onchange="selectAxios(event)" />
      <span>采用axios3：基于axios2包装，header追加<code>XHead3: 'third created'</code></span>
    </label>
  </div>
  <div class="operate">
    <button onclick="testAxios()">axios 开始</button>
    <button onclick="testFetch()">fetch 开始</button>
  </div>
  <hr />
  fetch并不好用，太底层了。请求header包装、响应消息解析，以及请求错误处理，什么都要自己封装！
</div>
<script type="module">
  import 'https://unpkg.zhimg.com/axios@1.3.2/dist/axios.min.js';
  // #region 计算url
  const CONTEXT = '/vanilla/';
  const href = window.location.href;
  let $host = 'http://localhost:1240/';
  if (new RegExp(CONTEXT).test(href)) {
    $host = href.split(CONTEXT)[0] + CONTEXT;
  }
  const url = $host + 'slow-api' + '/post2';
  // #endregion

  // #region 实现 abort-toggle 和 发送data、设置delay
  let abortFlag = false;
  window.toggle = (e) => {
    abortFlag = e.target.checked;
  };

  let start = 1;
  const generateData = () => {
    const arr = Array(5120)
      .fill(1)
      .map((_e, i) => i + start);
    start++;
    return { a: 1, b: arr };
  };

  let delay = 50;
  window.changeDelay = (e) => {
    delay = e.target.valueAsNumber;
  };
  // #endregion

  // #region 三种axios切换
  const axios1 = axios.create({
    headers: {
      XHead1: 'first created',
    },
  });
  const axios2 = axios1.create({
    headers: {
      XHead2: 'second created',
    },
  });
  const axios3 = axios2.create({
    headers: {
      XHead3: 'third created',
    },
  });

  let selectedAxios = axios1;
  window.selectAxios = (e) => {
    selectedAxios = { 1: axios1, 2: axios2, 3: axios3 }[e.target.value];
  };
  // #endregion

  window.testAxios = () => {
    const { token, cancel } = axios.CancelToken.source();
    selectedAxios.post(url, generateData(), { cancelToken: token }).then((res) => {
      console.log('success!=====', res);
    });
    setTimeout(() => {
      abortFlag && cancel('取消测试');
    }, delay);
  };

  window.testFetch = () => {
    const controller = new AbortController();
    const signal = controller.signal;
    const cancel = controller.abort.bind(controller); // 必须bind才有效

    fetch(url, {
      method: 'post',
      body: JSON.stringify(generateData()),
      headers: { 'content-type': 'application/json', Accept: 'application/json, text/plain, */*' },
      signal,
    })
      .then((res) => res.text())
      .then((res) => {
        console.log('success!=====', { data: res });
      })
      .catch((err) => {
        if (err.name === 'AbortError') {
          err = new Error(signal.reason, { name: err.name });
        }
        throw err;
      });

    setTimeout(() => {
      abortFlag && cancel('取消测试');
    }, delay);
  };
</script>
<hr>
<style>
  @keyframes moveLR {
    from {
      left: -5%;
    }

    to {
      left: 95%;
    }
  }

  .wrapper {
    height: 100px;
    border: 1px solid red;
    position: relative;
    overflow: hidden;
  }

  .tar {
    width: 10%;
    height: 100%;
    background-color: cadetblue;
    position: absolute;
    animation: moveLR 3s linear both;

    animation-play-state: paused;
  }
</style>
<div class="wrapper" onclick="onclickFn()">
  <div id="tar" class="tar" style="--delay:-1s;"></div>
</div>
<script>
  const div = document.getElementById('tar')
  div.style.animationDelay = '-1000ms'
  var onclickFn = () => {
    div.style.animationDelay = '-900ms'
  }

</script>